#include <stdio.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <sys/sem.h>

struct msg
{
    char buf[32];
};

union semun
{
    int val;
};

struct msg *p;
int shmid=0;
key_t key;

int FtokCreate()
{
    key=ftok("./app",'a');
    if (-1==key)
    {
        perror("ftok err\n");
        return -1;
    }
    shmid = shmget(key,128,IPC_CREAT|IPC_EXCL|0666);
    if (-1==shmid)
    {
        if (EEXIST == errno)
        {
            shmid=shmget(key,128,0666);
        }
        else
        {
            perror("shmget err\n");
            return -1;
        }
    }
    p=(struct msg*)shmat(shmid,NULL,0);
    if(p==(struct msg*)-1)
    {
        perror("shmat err\n");
        return -1;
    }
    return 0;
}

int main(int argc,char const* argv[])
{
    FtokCreate();
    int semid=semget(key,2,IPC_CREAT|IPC_EXCL|0666);
    if (-1==semid)
    {
        if (EEXIST==errno)
        {
            semid=semget(key,2,0666);
        }
        else
        {
            printf("semget err\n");
            return -1;
        }
    }

    union semun sem;
    sem.val=1;
    semctl(semid,0,SETVAL,sem);
    struct sembuf sb;
    sb.sem_num=0;
    semop(semid,&sb,1);
    while (1)
    {
        if(sem.val==1)
        {
            printf("please input data:");
            scanf("%s",p->buf);
            sb.sem_num=0;
            sb.sem_op=-1;
            sb.sem_flg=0;
            semop(semid,&sb,1);
            printf("%d\n",semctl(semid,0,GETVAL));
            printf("%d\n",semctl(semid,1,GETVAL));
        }
        if(strcmp("quit",p->buf)==0)
        {
            sem.val-=2;
            break;
        }
    }

    shmdt(p);

    shmctl(shmid,IPC_RMID,NULL);
    

    return 0;
}